<script lang="tsx">
import { defineComponent, onMounted, computed, ref, nextTick, watch } from 'vue';
import ObsImage from '#/components/obsImage.vue';
import { Eye, Download } from '@vben/icons'
import { formatNumberWithCommas } from '#/utils/formatNumber';
import Empty from '../empty.vue';
import playIcon from '#/assets/images/play.png';
import { $t } from '#/locales';
interface Props {
  allMaterialData: any[];
  handleViewDetail: (data: any) => void;
}

export default defineComponent({
  name: 'AllMaterial',
  props: {
    allMaterialData: {
      type: Array as () => any[],
      default: () => []
    },
    handleViewDetail: {
      type: Function,
      required: true
    }
  },
  setup(props: Props) {
    const getTotalViews = computed(() => {
      return (data: any) => {
        console.log(data);
        return formatNumberWithCommas(data.initialViews + data.views);
      }
    });

    // 存储每个元素的引用
    const descriptionRefs = ref<Record<string, HTMLElement>>({});
    // 存储每个元素是否被截断的状态
    const truncatedStates = ref<Record<string, boolean>>({});

    // 设置元素引用
    const setDescriptionRef = (el: any, id: string) => {
      if (el && el instanceof HTMLElement) {
        descriptionRefs.value[id] = el;
        // 检查是否被截断
        checkTruncation(id);
      }
    };

    // 检查文本是否被截断
    const checkTruncation = (id: string) => {
      const element = descriptionRefs.value[id];
      if (element) {
        // 检查元素的实际高度是否大于行高 * 行数
        const lineHeight = parseInt(window.getComputedStyle(element).lineHeight);
        const maxHeight = lineHeight * 2; // 两行的高度
        truncatedStates.value[id] = element.scrollHeight > maxHeight;
      }
    };

    // 判断是否显示 tooltip
    const isTextTruncated = (id: string) => {
      return truncatedStates.value[id] || false;
    };

    onMounted(() => {
      // 组件挂载后检查所有元素
      nextTick(() => {
        Object.keys(descriptionRefs.value).forEach(checkTruncation);
      });
    });

    // 监听数据变化，重新检查截断状态
    watch(() => props.allMaterialData, () => {
      nextTick(() => {
        Object.keys(descriptionRefs.value).forEach(checkTruncation);
      });
    }, { deep: true });

    return () => (
      <div class="all-material-container">
        <div class="dynamics-list">
          {console.log(props.allMaterialData)}
          {props.allMaterialData && props.allMaterialData.length > 0 ? (
            props.allMaterialData.map((item) => (
              <div key={item.id} class="dynamics-item">
                <div class="item-image">
                  <ObsImage src={item.img} alt={item.title} imgStyle={{ width: '250px', height: '140px' }} />
                  {item.fileType === 'vid' && (
                    <div class="item-image-mask" >
                      <img src={playIcon} alt="play" />
                    </div>
                  )}
                </div>
                <div class="item-content">
                  <h3 class="item-title">{item.title}</h3>
                  <el-tooltip 
                    content={item.content} 
                    placement="top" 
                    popper-class="custom-tooltip"
                    disabled={!isTextTruncated(item.id)}
                  >
                    <p 
                      class="item-description" 
                      ref={(el) => setDescriptionRef(el, item.id)}
                    >
                      {item.content}
                    </p>
                  </el-tooltip>
                  <div class="item-meta">
                    <div class="flex items-center gap-2 text-[14px]">
                      <span class="item-date mr-[24px]">{item.date}</span>
                      {item.fileType === 'vid' && (
                        <Eye class="w-[12px] h-[12px] text-[#595959]" />
                      )}
                      {item.fileType !== 'vid' && (
                        <Download class="w-[12px] h-[12px] text-[#595959]" />
                      )}
                      {item.fileType === 'vid' && (
                        <span class="item-tag">{getTotalViews.value(item)}</span>
                      )}
                      {item.fileType !== 'vid' && (
                        <span class="item-tag">{formatNumberWithCommas(item.viewCount)}</span>
                      )}
                    </div>
                    <div class="flex items-center gap-2 text-[14px]">
                      {item.fileType === 'vid' && (
                        <el-button plain onClick={() => props.handleViewDetail(item)}>{$t('competition.training.watchVideo')}</el-button>
                      )}
                      {item.fileType !== 'vid' && (
                        <el-button loading={item.loading} plain onClick={() => props.handleViewDetail(item)}>{$t('competition.training.downloadFile')}</el-button>
                      )}
                    </div>
                  </div>
                </div>
              </div>
            ))
          ) : (
            <Empty />
          )}
        </div>
      </div>
    );
  }
})
</script>

<style scoped>
/* 列样式 */
.dynamics-list {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.dynamics-item {
  display: flex;
  gap: 8px;
  padding: 8px;
  background: white;
  border: 1px solid #f0f0f0;
  border-radius: 16px;
  transition: all 0.3s ease;
  cursor: pointer;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);

}

.dynamics-item:hover {
  border-color: #667eea;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.1);
  transform: translateY(-2px);
}

.item-image {
  flex-shrink: 0;
  width: 245px;
  height: 140px;
  border-radius: 8px;
  overflow: hidden;
  position: relative;
}

.item-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.item-image-mask {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 96px;
  height: 96px;
  border-radius: 8px;
}

.item-content {
  flex: 1;
  display: flex;
  padding: 8px;
  flex-direction: column;
  justify-content: space-between;
}

.item-title {
  font-size: 18px;
  font-weight: 500;
  color: #191919;
  margin: 0 0 12px 0;
  line-height: 26px;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.item-description {
  font-size: 14px;
  color: #AEAEAE;
  margin: 0 0 18px 0;
  line-height: 22px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.item-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #AEAEAE;
}

.item-date {
  font-size: 14px;
}

.item-tag {
  font-size: 12px;
}

/* 自定义 tooltip 样式 */
:global(.custom-tooltip) {
  max-width: 500px !important;
  min-width: 200px !important;
}

:global(.custom-tooltip .el-tooltip__content) {
  word-wrap: break-word;
  white-space: pre-wrap;
  line-height: 1.5;
  padding: 8px 12px;
}


@media (max-width: 768px) {
  .all-material-container {
    padding: 20px;
  }

  .dynamics-item {
    flex-direction: column;
  }

  .item-image {
    width: 100%;
    height: 200px;
  }
}
</style>
